package cn.labbook.bluetooth.util.weixin;

import cn.labbook.bluetooth.constant.WeiXinConstants;
import cn.labbook.bluetooth.util.StringUtils;
import cn.labbook.bluetooth.util.http.HttpRequestUtils;
import cn.labbook.bluetooth.util.weixin.vo.AccessTokenVO;
import cn.labbook.bluetooth.util.weixin.vo.GenerateSchemeVO;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import lombok.extern.slf4j.Slf4j;

import java.util.Objects;

/**
 * @Author: zhangyang
 * @Date: 2023/4/28 17:03
 * @Desc: 微信请求工具
 */
@Slf4j
public class WeiXinRequestUtils {

    public static void main(String[] args) {
        System.out.println(getScheme());
    }

    /**
     * 获取token地址
     */
    private static final String GET_ACCESS_TOKEN_URL = "https://api.weixin.qq.com/cgi-bin/token";

    private static final String GET_SCHEME_URL = "https://api.weixin.qq.com/wxa/generatescheme";


    public static String getScheme() {
        String accessToken = getAccessToken();
        if (StringUtils.isBlank(accessToken)) {
            return null;
        }
        return getScheme(accessToken);
    }

    public static String getScheme(String accessToken) {
        if (StringUtils.isBlank(accessToken)) {
            return null;
        }

        String param = "?access_token=" + accessToken;
        String result = HttpRequestUtils.sendPostRequest(GET_SCHEME_URL + param, null);
        GenerateSchemeVO generateSchemeVO = JSONObject.parseObject(result, new TypeReference<GenerateSchemeVO>(){});
        if (Objects.isNull(generateSchemeVO)) {
            log.error("获取scheme码失败，generateSchemeVO is null");
            return null;
        }
        if (!Objects.equals(GenerateSchemeVO.ErrCode.SUCCESS.getCode(), generateSchemeVO.getErrcode())) {
            log.error("获取scheme码失败，result:" + result);
            return null;
        }
        return generateSchemeVO.getOpenlink();
    }

    /**
     * 获取token
     *
     * @return  token
     */
    public static String getAccessToken() {
        String param = "appid="
                + WeiXinConstants.APP_ID + "&secret=" + WeiXinConstants.SECRET + "&grant_type=client_credential";
        String result = HttpRequestUtils.sendPostRequest(GET_ACCESS_TOKEN_URL, param);
        if (StringUtils.isBlank(result)) {
            log.error("获取微信token失败，result is null");
            return null;
        }

        AccessTokenVO accessTokenVO = JSON.parseObject(result, new TypeReference<AccessTokenVO>(){});
        if (Objects.isNull(accessTokenVO)) {
            log.error("获取微信token失败，result:" + result);
            return null;
        }
        return accessTokenVO.getAccess_token();
    }

}
